from models.models import User
from service.BaseService import BaseService
from sqlmodel import Session, select
from core.Utils import generate_uuid, en_password
from typing import Optional

class UserService(BaseService[User]):
    def __init__(self):
        super().__init__(User)

    def get_user_by_id(self, user_id: str):
        statement = select(User).where(User.user_id == user_id)
        return self.session.exec(statement).first()

    def get_user_by_username(self, username: str):
        statement = select(User).where(User.username == username)
        return self.session.exec(statement).first()

    def create_user(self, username: str, password: str) -> User:
        user_id = generate_uuid()  # 生成用户ID
        hashed_password = en_password(password)  # 加密密码
        new_user = User(user_id=user_id, username=username,
                        password=hashed_password, money=0.0, nick_name=username, create_by=user_id, update_by=user_id)
        return self.create(new_user)

    def update_password_by_username(self, username: str, new_password: str) -> bool:
        user = self.get_user_by_username(username)
        if user:
            # 更新密码
            user.password = en_password(new_password)
            self.session.add(user)
            self.session.commit()
            return True
        return False

    def update_user_status(self, user_id: str):
        user = self.get_user_by_id(user_id)
        if user:
            user.user_status = 1 if user.user_status == 0 else 0
            self.session.add(user)
            self.session.commit()
            return True
        return False


    def update_user_role(self, user_id: str, role_id: str):
        user = self.get_user_by_id(user_id)
        if user:
            user.role_id = role_id
            self.session.add(user)
            self.session.commit()
            return True
        return False

    def get_user_list(self, page: int, page_size: int, user_status: Optional[int] = None,
                      user_id: Optional[str] = None):
        filters = []
        # 添加过滤条件
        if user_status is not None:
            filters.append(User.user_status == user_status)
        if user_id is not None:
            filters.append(User.user_id == user_id)


        # 获取分页数据
        user_list, total = self.get_paginated(page, page_size, filters)
        return user_list, total









